<?php
function create_phpbb_user($username, $new_password, $email){
	global $db;
	
			$username = str_replace("\'", "''", $username);
			$new_password = str_replace("\'", "''", $new_password);
			$email = str_replace("\'", "''", $email);

			$sql = "SELECT MAX(user_id) AS total FROM " . USERS_TABLE;
			if ( !($result = $db->sql_query($sql)) )
			{
				message_die(GENERAL_ERROR, 'Could not obtain next user_id information', '', __LINE__, __FILE__, $sql);
			}

			if ( !($row = $db->sql_fetchrow($result)) )
			{
				message_die(GENERAL_ERROR, 'Could not obtain next user_id information', '', __LINE__, __FILE__, $sql);
			}
			$user_id = $row['total'] + 1;

			$sql = "INSERT INTO " . USERS_TABLE . "	(user_id, username, user_regdate, user_password, user_email, user_active)
				VALUES ($user_id, '" . $username . "', " . time() . ", '" . $new_password . "', '" . $email . "', 1)";

			if ( !($result = $db->sql_query($sql)) )
			{
				message_die(GENERAL_ERROR, 'Could not insert data into users table', '', __LINE__, __FILE__, $sql);
			} else {
				//echo "User " . $username . " created.";
			}

}	


function phpbb_login($username, $password, $email, $return, $counter, $PAGE_INDEX){
		global $db, $globals, $user_ip;
		$sql = "SELECT user_id, username, user_password, user_active, user_level, user_login_tries, user_last_login_try
			FROM " . USERS_TABLE . "
			WHERE username = '" . str_replace("\\'", "''", $username) . "'";
			//echo $sql;
		if ( !($result = $db->sql_query($sql)) )
		{
			message_die(GENERAL_ERROR, 'Error in obtaining userdata', '', __LINE__, __FILE__, $sql);
		}

		if( $row = $db->sql_fetchrow($result) )
		{
			$userid = $row['user_id'];
			$autologin = ( isset($HTTP_POST_VARS['autologin']) ) ? TRUE : 0;
			$admin = (isset($HTTP_POST_VARS['admin'])) ? 1 : 0;
			$session_id = session_begin($userid, $user_ip, $PAGE_INDEX, FALSE, $autologin, $admin);
			header('Location: ' . $return);
			die();
		} else {

			if($counter == 0){
				create_phpbb_user($username, $password, $email);
				phpbb_login($username, $password, $email, $return, 1, $PAGE_INDEX);
			}
		}
}

?>